//
//  SINARegisterInputCodeViewController.m
//  sinashebao
//
//  Created by  androidlongs on 2018/1/25.
//  Copyright © 2018年  androidlongs. All rights reserved.
//

#import "SINARegisterInputCodeViewController.h"
#import "SINACircularBeadUtils.h"
#import "SINAUiviewClickLiserner.h"
#import <SMS_SDK/SMSSDK.h>
#import "SINARegisterSetPasswordViewController.h"
#import "SINACalendarUtils.h"

@interface SINARegisterInputCodeViewController ()
@property (weak, nonatomic) IBOutlet UILabel *showPhoneLabel;
//倒计时
@property (weak, nonatomic) IBOutlet UILabel *timeFlagLabel;
//获取验证码按钮
@property (weak, nonatomic) IBOutlet UILabel *getCodeLabel;
//下一步
@property (weak, nonatomic) IBOutlet UIButton *nextLabel;
@property (weak, nonatomic) IBOutlet UITextField *inputCodeField;

@property (strong, nonatomic) NSTimer *timer;

@property(nonatomic,assign) NSInteger currentTime;

//测试 不需要验证
@property(nonatomic,assign) BOOL isTest;
@end

@implementation SINARegisterInputCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.pageType==0) {
        self.navigationItem.title =@"注册";
    }else if(self.pageType==1){
        self.navigationItem.title =@"找回密码";
    }

    if (UI_IS_IPHONE6PLUS) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bar_plus_bg"]  forBarMetrics:UIBarMetricsDefault];
    } else {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bar_bg"]  forBarMetrics:UIBarMetricsDefault];
    }
    
    self.isTest = isTestMsgCode;
    self.navigationController.navigationBar.barTintColor = baseSelectColor;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [SINACircularBeadUtils makeCircularBead:2 andView:self.getCodeLabel andIsSetBackground:YES];
    [SINACircularBeadUtils makeCircularBead:2 andView:self.nextLabel andIsSetBackground:YES];
    
    self.timeFlagLabel . hidden = YES;
    
    __weak typeof(self) weakSelf = self;
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.getCodeLabel andWithBlick:^(UIView *view) {
        if (weakSelf.currentTime==60) {
            [weakSelf sendCodeFunction];
        }
        
    }];
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.nextLabel andWithBlick:^(UIView *view) {
        [weakSelf commidCodeFunction];
    }];
    // 创建定时器
    
    [self.getCodeLabel setBackgroundColor:baseButtonBackGroundColor];
    [self.nextLabel setBackgroundColor:baseButtonBackGroundColor];
    
    NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timeFlagFunction) userInfo:nil repeats:YES];
    
    self.timer = timer;
    
    self.currentTime=60;
}

-(void)viewWillAppear:(BOOL)animated{
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    NSString *getCodeTime=[userDefaults objectForKey:@"getCodeTime"];
    NSString *preCodeTime=[userDefaults objectForKey:@"preCodeTime"];
    
    DLog(@"保存的验证码剩余时间 %@",getCodeTime);
    if (getCodeTime!=nil&&![getCodeTime isEqualToString:@""]) {
        //有时间
        NSInteger preTime = [getCodeTime integerValue];
        //当前时间
        NSInteger currentTime =[[SINACalendarUtils currentTimeStr] integerValue];
        //时间差
        NSInteger flagTime = (currentTime - preTime)/1000;
        
        NSString *secondTime = [NSString stringWithFormat:@"%02ld",flagTime%60];
        
        
        DLog(@"发送验证码剩余时间 %ld %ld %@",(long)flagTime,(long)currentTime,secondTime);
        if ([secondTime integerValue]<0||[secondTime integerValue]>60) {
            self.currentTime=60;
            self.timeFlagLabel.hidden=YES;
            self.getCodeLabel.backgroundColor=baseButtonBackGroundColor;
            [userDefaults setObject: [NSString stringWithFormat:@"%@",@""] forKey:@"getCodeTime"];
            [userDefaults synchronize];
        }else if(0<=[secondTime integerValue]&&[secondTime integerValue]<=60){
            self.currentTime=[preCodeTime integerValue]-[secondTime integerValue];
            self.timeFlagLabel.hidden=NO;
            self.getCodeLabel.backgroundColor=[UIColor colorWithHexString:@"#eeeeee"];
            // 将定时器添加到runloop中，否则定时器不会启动
            [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        }
    }
    
}

-(void)viewDidDisappear:(BOOL)animated{
    DLog(@"发送验证码剩余时间 %ld",(long)self.currentTime);
    [self.timer invalidate];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if (self.currentTime!=60) {
        NSString *currentTime =[SINACalendarUtils currentTimeStr];
        DLog(@"保存剩余时间 %@",currentTime);
        [userDefaults setObject: currentTime forKey:@"getCodeTime"];
        [userDefaults setObject: [NSString stringWithFormat:@"%ld",(long)self.currentTime] forKey:@"preCodeTime"];
        [userDefaults synchronize];
    }else{
        [userDefaults setObject: @"" forKey:@"getCodeTime"];
        [userDefaults setObject: [NSString stringWithFormat:@"%ld",(long)self.currentTime] forKey:@"preCodeTime"];
        [userDefaults synchronize];
    }
}

-(void)timeFlagFunction{
    self.currentTime--;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if (((long)self.currentTime)==0) {
        self.timeFlagLabel.text=[NSString stringWithFormat:@"--秒后重新发送"];
    } else {
        self.timeFlagLabel.text=[NSString stringWithFormat:@"%ld秒后重新发送",(long)self.currentTime];
    }
    
    if (self.currentTime<=0) {
        [self.timer invalidate];
        self.currentTime=60;
        self.timeFlagLabel.hidden=YES;
        self.getCodeLabel.backgroundColor=baseButtonBackGroundColor;
        [userDefaults setObject: [NSString stringWithFormat:@"%@",@""] forKey:@"getCodeTime"];
        [userDefaults synchronize];
    }
}
//发送验证码
-(void) sendCodeFunction{
    __weak typeof(self) weakSelf = self;
    if (self.isTest) {
        weakSelf.showPhoneLabel.text=[NSString stringWithFormat:@"验证码已发送至%@",self.phone];
        weakSelf.timeFlagLabel.hidden=NO;
        weakSelf.currentTime=60;
        weakSelf.getCodeLabel.backgroundColor=[UIColor colorWithHexString:@"#eeeeee"];
        // 将定时器添加到runloop中，否则定时器不会启动
        [[NSRunLoop mainRunLoop] addTimer:weakSelf.timer forMode:NSRunLoopCommonModes];
        return;
    }
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.phone zone:@"86"  result:^(NSError *error) {
        
        if (!error)
        {
            // 请求成功
            DLog(@"请求成功");
            weakSelf.showPhoneLabel.text=[NSString stringWithFormat:@"验证码已发送至%@",self.phone];
            weakSelf.timeFlagLabel.hidden=NO;
            weakSelf.currentTime=60;
            weakSelf.getCodeLabel.backgroundColor=[UIColor colorWithHexString:@"#eeeeee"];
            // 将定时器添加到runloop中，否则定时器不会启动
            [[NSRunLoop mainRunLoop] addTimer:weakSelf.timer forMode:NSRunLoopCommonModes];
        }
        else
        {
            // error
            // error
            DLog(@"请求error");
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"发送验证码失败" sureBtn:@"确定"
                                                                 cancleBtn:nil];
            [alertView showXLAlertView];
            return;
        }
    }];
}

//提交短信验证码
-(void)commidCodeFunction{
    if (self.isTest) {
        
        WeakSelf;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            SINARegisterSetPasswordViewController *setPasswordController=[[SINARegisterSetPasswordViewController alloc]initWithNibName:@"SINARegisterSetPasswordViewController" bundle:nil];
            setPasswordController.phone=weakSelf.phone;
             setPasswordController.pageType=weakSelf.pageType;
            setPasswordController.otherLoginTag = self.otherLoginTag;
            [weakSelf.navigationController pushViewController:setPasswordController animated:YES];
        });
        
        
        return;
    }
    NSString *code = self.inputCodeField.text;
    if (code==nil||[code length]<1) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"请输入验证码" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    
    [SMSSDK commitVerificationCode:code phoneNumber:self.phone zone:@"86" result:^(NSError *error) {
        
        if (!error)
        {
           
            // 验证成功
            WeakSelf;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                SINARegisterSetPasswordViewController *setPasswordController=[[SINARegisterSetPasswordViewController alloc]initWithNibName:@"SINARegisterSetPasswordViewController" bundle:nil];
                setPasswordController.phone=weakSelf.phone;
                setPasswordController.pageType=weakSelf.pageType;
                setPasswordController.otherLoginTag = self.otherLoginTag;
                [weakSelf.navigationController pushViewController:setPasswordController animated:YES];
            });
        }
        else
        {
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"验证码验证失败" sureBtn:@"重新验证"
                                                                 cancleBtn:nil];
            [alertView showXLAlertView];
            return;
            
        }
    }];
}

-(void)viewDidAppear:(BOOL)animated{
     self.navigationController.navigationBarHidden = NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
